import { defineConfig, loadEnv } from 'vite';
import { createHtmlPlugin } from 'vite-plugin-html';
import vue from '@vitejs/plugin-vue';
import legacy from '@vitejs/plugin-legacy';
import browserslist from 'browserslist';
import { setUpENV } from './vite';
import * as path from 'path';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { TDesignResolver } from 'unplugin-vue-components/resolvers';
import UnoCSS from 'unocss/vite';
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), '');
  const APP_ENV = setUpENV(env, 'VITE_APP');

  return {
    define: {
      __APP_ENV__: JSON.stringify(APP_ENV),
    },
    plugins: [
      vue(),
      UnoCSS(),
      AutoImport({
        imports: ['vue', 'vue-i18n', 'vue-router', 'pinia'],
        dts: path.resolve(__dirname, 'types/auto-imports.d.ts'),
        resolvers: [TDesignResolver({ library: 'vue-next' })],
      }),
      createSvgIconsPlugin({
        // 要缓存的图标文件夹
        iconDirs: [path.resolve(__dirname, 'src/assets/icons/svg')],
        // 执行 icon-name 的格式
        symbolId: 'icon-[name]',
      }),
      Components({
        dts: path.resolve(__dirname, 'types/component-imports.d.ts'),
        resolvers: [TDesignResolver({ library: 'vue-next' })],
      }),
      legacy({
        targets: browserslist.loadConfig({ path: path.resolve(__dirname, '.') }),
      }),
      createHtmlPlugin({
        minify: true,
        inject: {
          data: APP_ENV,
        },
      }),
    ],
    resolve: {
      alias: {
        '@': path.resolve(__dirname, '.', 'src'),
      },
    },
    server: {
      host: APP_ENV.VITE_APP_HOST,
      port: APP_ENV.VITE_APP_POST,
      proxy: {
        [APP_ENV.VITE_APP_API_PREFIX]: {
          target: APP_ENV.VITE_APP_API,
          changeOrigin: true,
          rewrite: (path) => path.replace(APP_ENV.VITE_APP_API_PREFIX, ''),
        },
      },
    },
  };
});
